package com.hebeu.xwl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hebeu.xwl.dao.SaltDao;
import com.hebeu.xwl.dao.UserDao;
import com.hebeu.xwl.pojo.AdminSalt;
import com.hebeu.xwl.pojo.Saltable;
import com.hebeu.xwl.pojo.User;
import com.hebeu.xwl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl extends ServiceImpl<UserDao,User> implements UserService {

    @Autowired
    SaltDao saltDao;

    public User getUserById(int id)
    {
        return baseMapper.selectById(id);
    }



    @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
    public int findMAxArticle(int userId){
        return baseMapper.selectById(userId).getMaxArticle();
    }

    public String findSalt(String userAccount){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, userAccount);
        User user = baseMapper.selectOne(wrapper);
        if(user!=null)
        {
            //获取盐
            return saltDao.selectById(user.getUserId()).getSalt();
        }
        return null;
    }
    public User findUser(String account){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount,account);
        User user = baseMapper.selectOne(wrapper);
        return user;
        //return baseMapper.selectById(userId);
    }
    public String findPassword(String account){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, account);
        User user = baseMapper.selectOne(wrapper);
        String password = user.getPassword();
        if(password!=null){
            return password;
        }
        return null;
    }

    @Override
    @Transactional
    public Boolean insertUser(User user,String salt) {
        user.setMaxBatch(5);
        user.setMaxArticle(10000);
        baseMapper.insert(user);
        User user1 = this.findUser(user.getAccount());
        int insert = saltDao.insert(new Saltable(user1.getUserId(), salt));
        return insert==1;
    }

    @Override
    public void UpdatePassword(String email, String password) {
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.eq("account",email).set("password",password);
        baseMapper.update(null, wrapper);
        return;
    }

    @Override
    @Transactional
    public int deleteById(int id) {
        saltDao.deleteById(id);
        return  baseMapper.deleteById(id);
    }

}
